<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;">
    <title>判断终端类型</title>
    <style>
        .box {
            margin: 130px 0;
        }

        body {
            background-color: rgb(204, 252, 252);
        }

        a {
            text-decoration: none;
            border: 2px pink solid;
            background-color: rgba(255, 192, 203, 0.678);
        }
    </style>
</head>

<body>
<div class="box">
    <h1 id="screen">
        你的终端类型为：{{ user }}
        <br>
        <br>
        终端屏幕宽度为：{{ screenWidth }}px
        <br>
        <br>
        <a href="./index.html">返回首页</a>
    </h1>
</div>
<script src="./js/vue.js"></script>

<script>
    new Vue({
        el: "#screen",
        //先在data中去定义一个记录宽度是属性
        data: {
            user: navigator.userAgent,
            screenWidth: window.innerWidth
        },
        // 我们需要将 resize 事件在 vue mounted 的时候去挂载一下它的方法
        mounted () {
            const that = this
            window.onresize = () => {
                return (() => {
                    window.screenWidth = window.innerWidth
                    that.screenWidth = window.screenWidth
                })()
            }
        },
        // watch 去监听这个属性值的变化，如果发生变化则讲这个val传递给this.screenWidth
        watch: {
            screenWidth (val) {
                this.screenWidth = val
                // 优化 因为频繁触发 resize 函数，导致页面很卡的问题
                if (!this.timer) {
                    this.screenWidth = val
                    this.timer = true
                    let that = this
                    setTimeout(function () {
                        // that.screenWidth = that.$store.state.canvasWidth
                        console.log(that.screenWidth)
                        that.init()
                        that.timer = false
                    }, 400)
                }
            }
        }
    });
</script>
</body>

</html>